from multiprocessing.pool import ThreadPool
from threading import Thread
from os.path import exists
from invidious import *
import requests
import time
import sys

from plugins.core.plugin import Plugin
from plugins.core.pluginvideo import PluginVideo
from plugins.core.pluginplaylist import PluginPlaylist

sys.path.append("..")
from src.vobjects.item import Item
from src.vobjects.video import Video
from src.vobjects.channel import Channel
from src.vobjects.playlist import Playlist
from src.vobjects.basechannel import BaseChannel

from src.utils import *
from src.config import Config
from src.history import History
from ui.progressbar import ProgressBar

class InvidiousSubscriptions(Plugin):

    def __init__(self, history: History=History()):
        super().__init__(history=history)

        self.name = "Invidious: Subscriptions"
        self.is_query_required = False
        self.query_description = """"""

        self.config = Config()
        if exists(self.config.subs_path): self.SUBS_LIST = [i.strip('\n').split(',')[0] for i in open(self.config.subs_path)]
        else: self.SUBS_LIST = []
        self.subscriptions = list()
        self.sorted_sub_videos = list()

        self.flag = "-isb"
        self.full_flag = "--ivsubs"
        self.flag_help = "show all subscribed channels"
        self.flag_action = "store_true"

    def load_subscription(self, authorId=""):
        chn = self.invidious.get_channel(authorId)
        while chn == None:
            time.sleep(1)
            chn = self.invidious.get_channel(authorId)
        chn.convert(BaseChannel)
        item = chn.to_item()
        self.subscriptions.append(item)

        #==========> Update ProgressBar <==========#
        self.progressbar.increase_progress()
        self.progressbar.description = chn.author
        self.progressbar.big_description = self.invidious.get_working_mirror()+"/channel/"+authorId
        #==========================================#

    def load_subscriptions(self):
        if len(self.subscriptions) > 0 and not self.config.ReloadSubscribes: return
        self.subscriptions.clear()
        self.invidious.update_mirrors()

        #==========> Start ProgressBar <==========#
        self.progressbar = ProgressBar("Loading subscribes", 
                                       "", "", 0, len(self.SUBS_LIST), 40)
        th = Thread(target=self.progressbar.start_loop)
        th.start()
        #=========================================#

        pool = ThreadPool(processes=10)
        pool.map(self.load_subscription, self.SUBS_LIST)

        #==========> Kill ProgressBar <==========#
        self.progressbar.exit()
        #========================================#

        self.subscriptions = sort_channels_by_link_list(self.subscriptions, self.SUBS_LIST)      

    def get_subscriptions(self):
        self.load_subscriptions()
        return self.subscriptions

    def get_items_by_query(self, query: str=""):
        return list()

    def get_items(self):
        return self.get_subscriptions()


if __name__ == "__main__":
    al = InvidiousSubscriptions()

    items = al.get_items_by_query(query="мастера меча онлайн")
    for item in items:
        print(item.title, item.parent.url)




